<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class User extends Base
{
    // 会员首页
    public function index()
    {
        $title = "会员管理";

        $data = \app\admin\model\User::select();

        return view("user/index",[
            'title' => $title,
            'data' => $data
        ]);
    }

    // 修改会员名
    public function edit(int $id)
    {
        if(empty($id)){
            $this->error("参数错误",'/admin/user/index');
            die;
        }
        $title = "会员修改";

        $data = \app\admin\model\User::find($id);

        return view('/user/edit',[
            'title' => $title,
            'data' => $data
        ]);
    }

    // 更新会员名
    public function update(Request $request)
    {
        $data = $request->param();

        $rule = [
            'username' => 'require|token',
            'phone' => 'require',
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data))
        {
            $this->error($validate->getError());
        }

        $data['is_check'] = !empty($data['is_check']) ? 1 : 0;

        \app\admin\model\User::update($data,['id',$data['id']],true);

        $this->success("修改成功",'admin/user/index');

    }

    // 会员添加
    public function add()
    {
        $title = "会员添加";

        return view("/user/add",[
            'title' => $title
        ]);
    }

    // 增加会员
    public function insert(Request $request)
    {
        $data = $request->param();

        $rule = [
            'username|用户名' => 'require',
            'phone|手机号' => 'require|number',
            'password|密码' => 'require|min:5|confirm'
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data))
        {
            $this->error($validate->getError());
        }

        $data['is_check'] = !empty($data['is_check']) ? 1 : 0;

        # 获取当前时间
        $data['last_time_login'] = strtotime(date("Y-m-d h:i:s"));

        # 将密码改变成独有的MD5加密模式
        $data['password'] = indexpwd($data['password']);
        $data['password_confirm'] = indexpwd($data['password_confirm']);


        \app\admin\model\User::create($data,true);

        $this->success("添加成功",'admin/user/index');
    }

    // 删除会员
    public function delete(int $id)
    {
        if(empty($id))
        {
            $this->error("参数错误",'/admin/user/index');
            die;
        }

        \app\admin\model\User::destroy($id);

        $this->success("删除成功",'/admin/user/index');
    }
}

